import React, { useRef, useEffect, useState, useCallback } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three-stdlib';
import { Modal, Descriptions, Tag, Statistic, Card, Row, Col, Progress, Table, Spin } from 'antd';
import {
  DatabaseOutlined,
  HomeOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

// 电梯信息接口
interface ElevatorData {
  id: string;
  type: 'passenger' | 'freight' | 'emergency';
  status: 'normal' | 'maintenance' | 'error';
  floors: number[]; // 服务楼层
}

// 设备信息接口
interface DeviceData {
  id: string;
  name: string;
  type: 'elevator' | 'hvac' | 'security' | 'lighting' | 'fire_safety' | 'access_control';
  buildingId: string;
  buildingName: string;
  status: 'online' | 'offline' | 'maintenance' | 'error';
  location: string;
  lastMaintenance: string;
  nextMaintenance: string;
  manufacturer: string;
  model: string;
  installDate: string;
  energyConsumption?: number; // kWh
  operatingHours?: number;
}

// 楼宇数据接口
interface BuildingData {
  id: string;
  name: string;
  position: { x: number; y: number; z: number };
  floors: number;
  type: 'residential' | 'commercial' | 'office' | 'mixed';
  status: 'normal' | 'medium' | 'low';
  occupancy: number; // 入住率 0-100
  elevators: ElevatorData[]; // 电梯信息
}

// 华发一期模拟数据 - 根据Dashboard3D.tsx中的真实数据
const mockBuildingsDataPhase1: BuildingData[] = [
  {
    id: '1',
    name: '华发新城A座',
    position: { x: -50, y: 0, z: -30 },
    floors: 32,
    type: 'residential',
    status: 'normal',
    occupancy: 85,
    elevators: [
      { id: 'A1', type: 'passenger', status: 'normal', floors: Array.from({length: 32}, (_, i) => i + 1) },
      { id: 'A2', type: 'passenger', status: 'normal', floors: Array.from({length: 32}, (_, i) => i + 1) }
    ]
  },
  {
    id: '2',
    name: '华发新城B座',
    position: { x: -20, y: 0, z: -30 },
    floors: 28,
    type: 'residential',
    status: 'normal',
    occupancy: 92,
    elevators: [
      { id: 'B1', type: 'passenger', status: 'normal', floors: Array.from({length: 28}, (_, i) => i + 1) },
      { id: 'B2', type: 'passenger', status: 'maintenance', floors: Array.from({length: 28}, (_, i) => i + 1) }
    ]
  },
  {
    id: '3',
    name: '华发新城C座',
    position: { x: 10, y: 0, z: -30 },
    floors: 35,
    type: 'residential',
    status: 'medium',
    occupancy: 78,
    elevators: [
      { id: 'C1', type: 'passenger', status: 'normal', floors: Array.from({length: 35}, (_, i) => i + 1) },
      { id: 'C2', type: 'passenger', status: 'error', floors: Array.from({length: 35}, (_, i) => i + 1) },
      { id: 'C3', type: 'freight', status: 'normal', floors: [1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 35] }
    ]
  },
  {
    id: '4',
    name: '商业中心',
    position: { x: 40, y: 0, z: -10 },
    floors: 15,
    type: 'commercial',
    status: 'normal',
    occupancy: 95,
    elevators: [
      { id: 'D1', type: 'passenger', status: 'normal', floors: Array.from({length: 15}, (_, i) => i + 1) },
      { id: 'D2', type: 'passenger', status: 'normal', floors: Array.from({length: 15}, (_, i) => i + 1) },
      { id: 'D3', type: 'freight', status: 'normal', floors: [1, 2, 5, 10, 15] },
      { id: 'D4', type: 'emergency', status: 'normal', floors: Array.from({length: 15}, (_, i) => i + 1) }
    ]
  },
  {
    id: '5',
    name: '办公大楼',
    position: { x: -30, y: 0, z: 20 },
    floors: 25,
    type: 'office',
    status: 'normal',
    occupancy: 88,
    elevators: [
      { id: 'E1', type: 'passenger', status: 'normal', floors: Array.from({length: 25}, (_, i) => i + 1) },
      { id: 'E2', type: 'passenger', status: 'normal', floors: Array.from({length: 25}, (_, i) => i + 1) },
      { id: 'E3', type: 'freight', status: 'maintenance', floors: [1, 5, 10, 15, 20, 25] }
    ]
  },
  {
    id: '6',
    name: '综合体D座',
    position: { x: 20, y: 0, z: 30 },
    floors: 40,
    type: 'mixed',
    status: 'low',
    occupancy: 65,
    elevators: [
      { id: 'F1', type: 'passenger', status: 'normal', floors: Array.from({length: 40}, (_, i) => i + 1) },
      { id: 'F2', type: 'passenger', status: 'normal', floors: Array.from({length: 40}, (_, i) => i + 1) },
      { id: 'F3', type: 'passenger', status: 'error', floors: Array.from({length: 40}, (_, i) => i + 1) },
      { id: 'F4', type: 'freight', status: 'normal', floors: [1, 2, 5, 10, 15, 20, 25, 30, 35, 40] },
      { id: 'F5', type: 'emergency', status: 'normal', floors: Array.from({length: 40}, (_, i) => i + 1) }
    ]
  }
];

const mockDevicesDataPhase1: DeviceData[] = [
  // 华发新城A座设备
  { id: 'DEV001', name: '电梯A1', type: 'elevator', buildingId: '1', buildingName: '华发新城A座', status: 'online', location: '1号楼东侧', lastMaintenance: '2024-01-15', nextMaintenance: '2024-04-15', manufacturer: '奥的斯', model: 'Gen2-MR', installDate: '2020-03-10', operatingHours: 8760 },
  { id: 'DEV002', name: '电梯A2', type: 'elevator', buildingId: '1', buildingName: '华发新城A座', status: 'online', location: '1号楼西侧', lastMaintenance: '2024-01-15', nextMaintenance: '2024-04-15', manufacturer: '奥的斯', model: 'Gen2-MR', installDate: '2020-03-10', operatingHours: 8650 },
  { id: 'DEV003', name: '中央空调系统', type: 'hvac', buildingId: '1', buildingName: '华发新城A座', status: 'online', location: '地下室机房', lastMaintenance: '2024-02-01', nextMaintenance: '2024-05-01', manufacturer: '大金', model: 'VRV-X7', installDate: '2020-02-15', energyConsumption: 1250 },
  { id: 'DEV004', name: '门禁系统', type: 'access_control', buildingId: '1', buildingName: '华发新城A座', status: 'online', location: '大堂入口', lastMaintenance: '2024-01-20', nextMaintenance: '2024-07-20', manufacturer: '海康威视', model: 'DS-K1T671TM-3XF', installDate: '2020-04-01' },
  
  // 华发新城B座设备
  { id: 'DEV005', name: '客梯B1', type: 'elevator', buildingId: '2', buildingName: '华发新城B座', status: 'maintenance', location: 'B区1号梯', lastMaintenance: '2024-02-10', nextMaintenance: '2024-05-10', manufacturer: '三菱', model: 'NEXIEZ-MRL', installDate: '2019-08-20', operatingHours: 12500 },
  { id: 'DEV006', name: '货梯B2', type: 'elevator', buildingId: '2', buildingName: '华发新城B座', status: 'online', location: 'B区货梯', lastMaintenance: '2024-01-25', nextMaintenance: '2024-04-25', manufacturer: '三菱', model: 'ELENESSA', installDate: '2019-08-20', operatingHours: 9800 },
  { id: 'DEV007', name: '消防系统', type: 'fire_safety', buildingId: '2', buildingName: '华发新城B座', status: 'online', location: '各楼层', lastMaintenance: '2024-02-15', nextMaintenance: '2024-08-15', manufacturer: '海湾', model: 'GST-LD-8318', installDate: '2019-07-10' },
  { id: 'DEV008', name: '智能照明', type: 'lighting', buildingId: '2', buildingName: '华发新城B座', status: 'online', location: '公共区域', lastMaintenance: '2024-01-30', nextMaintenance: '2024-07-30', manufacturer: '飞利浦', model: 'CityTouch flex', installDate: '2019-09-05', energyConsumption: 850 },
  
  // 华发新城C座设备
  { id: 'DEV009', name: '高速电梯C1', type: 'elevator', buildingId: '3', buildingName: '华发新城C座', status: 'online', location: '东塔1号梯', lastMaintenance: '2024-02-05', nextMaintenance: '2024-05-05', manufacturer: '日立', model: 'NEXWAY', installDate: '2021-05-15', operatingHours: 6200 },
  { id: 'DEV010', name: '高速电梯C2', type: 'elevator', buildingId: '3', buildingName: '华发新城C座', status: 'error', location: '东塔2号梯', lastMaintenance: '2024-01-10', nextMaintenance: '2024-04-10', manufacturer: '日立', model: 'NEXWAY', installDate: '2021-05-15', operatingHours: 6150 },
  { id: 'DEV011', name: '安防监控', type: 'security', buildingId: '3', buildingName: '华发新城C座', status: 'online', location: '全楼监控', lastMaintenance: '2024-02-20', nextMaintenance: '2024-08-20', manufacturer: '大华', model: 'DH-IPC-HFW4433M-I2', installDate: '2021-04-20' },
  
  // 商业中心设备
  { id: 'DEV012', name: '客梯D1', type: 'elevator', buildingId: '4', buildingName: '商业中心', status: 'online', location: '西区1号梯', lastMaintenance: '2024-02-12', nextMaintenance: '2024-05-12', manufacturer: '蒂森克虏伯', model: 'synergy', installDate: '2018-11-10', operatingHours: 15600 },
  { id: 'DEV013', name: '客梯D2', type: 'elevator', buildingId: '4', buildingName: '商业中心', status: 'online', location: '西区2号梯', lastMaintenance: '2024-02-12', nextMaintenance: '2024-05-12', manufacturer: '蒂森克虏伯', model: 'synergy', installDate: '2018-11-10', operatingHours: 15450 },
  { id: 'DEV014', name: '中央空调', type: 'hvac', buildingId: '4', buildingName: '商业中心', status: 'online', location: '屋顶机房', lastMaintenance: '2024-01-28', nextMaintenance: '2024-04-28', manufacturer: '约克', model: 'YVWA', installDate: '2018-10-05', energyConsumption: 2100 },
  
  // 办公大楼设备
  { id: 'DEV015', name: '高速电梯E1', type: 'elevator', buildingId: '5', buildingName: '办公大楼', status: 'online', location: 'A座1号梯', lastMaintenance: '2024-02-08', nextMaintenance: '2024-05-08', manufacturer: '迅达', model: '7000', installDate: '2022-01-20', operatingHours: 4800 },
  { id: 'DEV016', name: '高速电梯E2', type: 'elevator', buildingId: '5', buildingName: '办公大楼', status: 'online', location: 'A座2号梯', lastMaintenance: '2024-02-08', nextMaintenance: '2024-05-08', manufacturer: '迅达', model: '7000', installDate: '2022-01-20', operatingHours: 4750 },
  { id: 'DEV017', name: 'BMS系统', type: 'hvac', buildingId: '5', buildingName: '办公大楼', status: 'online', location: '智能控制中心', lastMaintenance: '2024-02-18', nextMaintenance: '2024-08-18', manufacturer: '西门子', model: 'Desigo CC', installDate: '2022-02-10', energyConsumption: 1800 },
  
  // 综合体D座设备
  { id: 'DEV018', name: '超高速电梯F1', type: 'elevator', buildingId: '6', buildingName: '综合体D座', status: 'online', location: '核心筒1号梯', lastMaintenance: '2024-02-22', nextMaintenance: '2024-05-22', manufacturer: '东芝', model: 'SPACEL-GR', installDate: '2023-03-15', operatingHours: 2200 },
  { id: 'DEV019', name: '超高速电梯F2', type: 'elevator', buildingId: '6', buildingName: '综合体D座', status: 'online', location: '核心筒2号梯', lastMaintenance: '2024-02-22', nextMaintenance: '2024-05-22', manufacturer: '东芝', model: 'SPACEL-GR', installDate: '2023-03-15', operatingHours: 2150 },
  { id: 'DEV020', name: '货梯F4', type: 'elevator', buildingId: '6', buildingName: '综合体D座', status: 'online', location: '货运专用梯', lastMaintenance: '2024-02-25', nextMaintenance: '2024-05-25', manufacturer: '东芝', model: 'ELCOSMO', installDate: '2023-03-20', operatingHours: 1800 },
  { id: 'DEV021', name: '智能楼宇系统', type: 'hvac', buildingId: '6', buildingName: '综合体D座', status: 'online', location: '智控中心', lastMaintenance: '2024-03-01', nextMaintenance: '2024-09-01', manufacturer: '霍尼韦尔', model: 'EBI R200', installDate: '2023-04-01', energyConsumption: 2800 }
];

const Phase1View: React.FC = () => {
  const mountRef = useRef<HTMLDivElement>(null);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
  const controlsRef = useRef<OrbitControls | null>(null);
  const animationIdRef = useRef<number | undefined>(undefined);
  const startLoopRef = useRef<(() => void) | null>(null);
  
  const [isLoading, setIsLoading] = useState(true);
  const [selectedDevice, setSelectedDevice] = useState<DeviceData | null>(null);
  const [deviceModalVisible, setDeviceModalVisible] = useState(false);
  const [selectedBuilding, setSelectedBuilding] = useState<BuildingData | null>(null);
  const [buildingModalVisible, setBuildingModalVisible] = useState(false);

  // 获取楼宇颜色
  const getBuildingColor = useCallback((building: BuildingData): number => {
    switch (building.status) {
      case 'normal': return 0x4CAF50; // 绿色
      case 'medium': return 0xFF9800; // 橙色
      case 'low': return 0xF44336; // 红色
      default: return 0x9E9E9E; // 灰色
    }
  }, []);

  // 获取楼宇类型颜色
  const getBuildingTypeColor = useCallback((type: string): number => {
    switch (type) {
      case 'residential': return 0x2196F3; // 蓝色
      case 'commercial': return 0x9C27B0; // 紫色
      case 'office': return 0x607D8B; // 蓝灰色
      case 'mixed': return 0x795548; // 棕色
      default: return 0x9E9E9E;
    }
  }, []);

  // 获取电梯颜色
  const getElevatorColor = useCallback((elevator: ElevatorData): number => {
    switch (elevator.status) {
      case 'normal': return 0x00FF00; // 绿色
      case 'maintenance': return 0xFFFF00; // 黄色
      case 'error': return 0xFF0000; // 红色
      default: return 0x808080;
    }
  }, []);

  // 创建设备3D图标
  const createDeviceIcon = useCallback((device: DeviceData): THREE.Group => {
    const iconGroup = new THREE.Group();
    
    // 根据设备类型创建不同的3D图标
    switch (device.type) {
      case 'elevator':
        // 电梯图标 - 立方体带箭头
        const elevatorGeometry = new THREE.BoxGeometry(0.8, 1.2, 0.8);
        const elevatorMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x4CAF50 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const elevatorMesh = new THREE.Mesh(elevatorGeometry, elevatorMaterial);
        
        // 电梯门
        const doorGeometry = new THREE.PlaneGeometry(0.6, 1.0);
        const doorMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const doorMesh = new THREE.Mesh(doorGeometry, doorMaterial);
        doorMesh.position.z = 0.41;
        
        iconGroup.add(elevatorMesh);
        iconGroup.add(doorMesh);
        break;
        
      case 'hvac':
        // HVAC图标 - 圆柱体带风扇
        const hvacGeometry = new THREE.CylinderGeometry(0.6, 0.6, 0.4, 8);
        const hvacMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x2196F3 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const hvacMesh = new THREE.Mesh(hvacGeometry, hvacMaterial);
        
        // 风扇叶片
        for (let i = 0; i < 4; i++) {
          const bladeGeometry = new THREE.BoxGeometry(0.8, 0.1, 0.05);
          const bladeMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 });
          const bladeMesh = new THREE.Mesh(bladeGeometry, bladeMaterial);
          bladeMesh.rotation.z = (i * Math.PI) / 2;
          bladeMesh.position.y = 0.25;
          iconGroup.add(bladeMesh);
        }
        
        iconGroup.add(hvacMesh);
        break;
        
      case 'security':
        // 安防图标 - 摄像头形状
        const cameraGeometry = new THREE.BoxGeometry(0.4, 0.4, 0.8);
        const cameraMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x9C27B0 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const cameraMesh = new THREE.Mesh(cameraGeometry, cameraMaterial);
        
        // 镜头
        const lensGeometry = new THREE.CylinderGeometry(0.15, 0.15, 0.3, 8);
        const lensMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
        const lensMesh = new THREE.Mesh(lensGeometry, lensMaterial);
        lensMesh.rotation.x = Math.PI / 2;
        lensMesh.position.z = 0.55;
        
        iconGroup.add(cameraMesh);
        iconGroup.add(lensMesh);
        break;
        
      case 'lighting':
        // 照明图标 - 灯泡形状
        const bulbGeometry = new THREE.SphereGeometry(0.4, 8, 6);
        const bulbMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0xFFEB3B : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336,
          emissive: device.status === 'online' ? 0x444400 : 0x000000,
          emissiveIntensity: device.status === 'online' ? 0.3 : 0
        });
        const bulbMesh = new THREE.Mesh(bulbGeometry, bulbMaterial);
        
        // 灯座
        const baseGeometry = new THREE.CylinderGeometry(0.2, 0.3, 0.4, 8);
        const baseMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
        baseMesh.position.y = -0.6;
        
        iconGroup.add(bulbMesh);
        iconGroup.add(baseMesh);
        break;
        
      case 'fire_safety':
        // 消防图标 - 警报器形状
        const alarmGeometry = new THREE.ConeGeometry(0.5, 0.8, 8);
        const alarmMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0xFF5722 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const alarmMesh = new THREE.Mesh(alarmGeometry, alarmMaterial);
        
        // 警报灯
        const lightGeometry = new THREE.SphereGeometry(0.15, 8, 6);
        const lightMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFF0000,
          emissive: device.status === 'online' ? 0x440000 : 0x000000,
          emissiveIntensity: device.status === 'online' ? 0.5 : 0
        });
        const lightMesh = new THREE.Mesh(lightGeometry, lightMaterial);
        lightMesh.position.y = 0.5;
        
        iconGroup.add(alarmMesh);
        iconGroup.add(lightMesh);
        break;
        
      case 'access_control':
        // 门禁图标 - 门形状
        const doorFrameGeometry = new THREE.BoxGeometry(0.8, 1.2, 0.1);
        const doorFrameMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x607D8B : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const doorFrameMesh = new THREE.Mesh(doorFrameGeometry, doorFrameMaterial);
        
        // 门把手
        const handleGeometry = new THREE.SphereGeometry(0.08, 6, 4);
        const handleMaterial = new THREE.MeshLambertMaterial({ color: 0xFFD700 });
        const handleMesh = new THREE.Mesh(handleGeometry, handleMaterial);
        handleMesh.position.set(0.3, 0, 0.1);
        
        iconGroup.add(doorFrameMesh);
        iconGroup.add(handleMesh);
        break;
        
      default:
        // 默认设备图标 - 简单立方体
        const defaultGeometry = new THREE.BoxGeometry(0.6, 0.6, 0.6);
        const defaultMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x9E9E9E : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const defaultMesh = new THREE.Mesh(defaultGeometry, defaultMaterial);
        iconGroup.add(defaultMesh);
        break;
    }
    
    // 添加状态指示环
    const ringGeometry = new THREE.RingGeometry(0.8, 1.0, 16);
    const ringMaterial = new THREE.MeshLambertMaterial({ 
      color: device.status === 'online' ? 0x00FF00 : 
             device.status === 'maintenance' ? 0xFFFF00 : 
             device.status === 'offline' ? 0x666666 : 0xFF0000,
      side: THREE.DoubleSide,
      transparent: true,
      opacity: 0.6
    });
    const ringMesh = new THREE.Mesh(ringGeometry, ringMaterial);
    ringMesh.rotation.x = -Math.PI / 2;
    ringMesh.position.y = -0.8;
    iconGroup.add(ringMesh);
    
    return iconGroup;
  }, []);

  // 创建电梯3D模型
  const createElevator = useCallback((elevator: ElevatorData, buildingHeight: number): THREE.Group => {
    const elevatorGroup = new THREE.Group();
    
    // 电梯井道
    const shaftGeometry = new THREE.BoxGeometry(1.5, buildingHeight, 1.5);
    const shaftMaterial = new THREE.MeshLambertMaterial({ 
      color: 0x333333,
      transparent: true,
      opacity: 0.7
    });
    const shaftMesh = new THREE.Mesh(shaftGeometry, shaftMaterial);
    shaftMesh.position.y = buildingHeight / 2;
    
    // 电梯轿厢
    const carGeometry = new THREE.BoxGeometry(1.2, 2.5, 1.2);
    const carMaterial = new THREE.MeshLambertMaterial({ 
      color: getElevatorColor(elevator)
    });
    const carMesh = new THREE.Mesh(carGeometry, carMaterial);
    
    // 电梯门
    const doorGeometry = new THREE.PlaneGeometry(0.8, 2.0);
    const doorMaterial = new THREE.MeshLambertMaterial({ 
      color: 0x666666
    });
    const doorMesh = new THREE.Mesh(doorGeometry, doorMaterial);
    doorMesh.position.z = 0.61;
    
    // 创建轿厢组
    const carGroup = new THREE.Group();
    carGroup.add(carMesh);
    carGroup.add(doorMesh);
    
    // 设置轿厢初始位置（底层）
    carGroup.position.y = 2.5;
    
    // 状态指示灯
    const indicatorGeometry = new THREE.SphereGeometry(0.15, 8, 8);
    const indicatorMaterial = new THREE.MeshLambertMaterial({ 
      color: getElevatorColor(elevator),
      emissive: getElevatorColor(elevator),
      emissiveIntensity: 0.4
    });
    const indicatorMesh = new THREE.Mesh(indicatorGeometry, indicatorMaterial);
    indicatorMesh.position.set(0, buildingHeight + 1.5, 0);
    
    elevatorGroup.add(shaftMesh);
    elevatorGroup.add(carGroup);
    elevatorGroup.add(indicatorMesh);
    
    // 设置用户数据，包含动画相关信息
    elevatorGroup.userData = { 
      elevator, 
      building: null,
      carGroup: carGroup,
      buildingHeight: buildingHeight,
      currentFloor: 1,
      targetFloor: 1,
      isMoving: false,
      moveSpeed: 0.02,
      direction: 1, // 1 向上, -1 向下
      lastMoveTime: Date.now()
    };
    
    return elevatorGroup;
  }, [getElevatorColor]);

  // 初始化3D场景
  const initScene = useCallback(() => {
    if (!mountRef.current) return;

    const currentMount = mountRef.current;
    
    // 创建场景
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x000011);
    sceneRef.current = scene;

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      75,
      currentMount.clientWidth / currentMount.clientHeight,
      0.1,
      1000
    );
    camera.position.set(50, 50, 50);
    cameraRef.current = camera;

    // 创建渲染器（优化像素比与阴影尺寸）
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
    renderer.setSize(currentMount.clientWidth, currentMount.clientHeight);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    rendererRef.current = renderer;



    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(50, 50, 25);
    directionalLight.castShadow = true;
    // 降低阴影贴图尺寸以减少 GPU 占用
    directionalLight.shadow.mapSize.width = 1024;
    directionalLight.shadow.mapSize.height = 1024;
    scene.add(directionalLight);

    // 创建地面
    const groundGeometry = new THREE.PlaneGeometry(200, 200);
    const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x2F4F4F });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    ground.receiveShadow = true;
    scene.add(ground);

    // 创建网格
    const gridHelper = new THREE.GridHelper(200, 20, 0x444444, 0x444444);
    scene.add(gridHelper);

    // 创建楼宇
    mockBuildingsDataPhase1.forEach((building) => {
      const buildingGroup = new THREE.Group();
      
      // 主楼体
      const buildingHeight = building.floors * 3;
      const geometry = new THREE.BoxGeometry(8, buildingHeight, 8);
      const material = new THREE.MeshLambertMaterial({ 
        color: getBuildingColor(building),
        transparent: true,
        opacity: 0.8
      });
      const buildingMesh = new THREE.Mesh(geometry, material);
      buildingMesh.position.y = buildingHeight / 2;
      buildingMesh.castShadow = true;
      buildingMesh.receiveShadow = true;
      
      // 楼宇边框
      const edges = new THREE.EdgesGeometry(geometry);
      const lineMaterial = new THREE.LineBasicMaterial({ 
        color: 0xffffff,
        linewidth: 2
      });
      const wireframe = new THREE.LineSegments(edges, lineMaterial);
      wireframe.position.y = buildingHeight / 2;
      
      buildingGroup.add(buildingMesh);
      buildingGroup.add(wireframe);

      // 添加窗户装饰
      const windowMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x87CEEB,
        transparent: true,
        opacity: 0.7
      });
      
      // 窗框材质
      const windowFrameMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x8B4513,
        transparent: true,
        opacity: 0.9
      });
      
      // 在楼宇四面添加窗户
      for (let floor = 1; floor < building.floors; floor += 2) {
        for (let side = 0; side < 4; side++) {
          for (let window = 0; window < 3; window++) {
            // 窗户玻璃
            const windowGeometry = new THREE.BoxGeometry(0.8, 1.2, 0.1);
            const windowMesh = new THREE.Mesh(windowGeometry, windowMaterial);
            
            // 窗框
            const frameGeometry = new THREE.BoxGeometry(1.0, 1.4, 0.15);
            const frameMesh = new THREE.Mesh(frameGeometry, windowFrameMaterial);
            
            const floorY = floor * 3;
            const windowX = (window - 1) * 2;
            
            if (side === 0) { // 前面
              windowMesh.position.set(windowX, floorY, 4.1);
              frameMesh.position.set(windowX, floorY, 4.05);
            } else if (side === 1) { // 右面
              windowMesh.position.set(4.1, floorY, windowX);
              frameMesh.position.set(4.05, floorY, windowX);
            } else if (side === 2) { // 后面
              windowMesh.position.set(windowX, floorY, -4.1);
              frameMesh.position.set(windowX, floorY, -4.05);
            } else { // 左面
              windowMesh.position.set(-4.1, floorY, windowX);
              frameMesh.position.set(-4.05, floorY, windowX);
            }
            
            // 添加窗户反光效果（随机）
            if (Math.random() > 0.7) {
              const reflectionMaterial = new THREE.MeshLambertMaterial({ 
                color: 0xFFFFFF,
                transparent: true,
                opacity: 0.3,
                emissive: 0xFFFFFF,
                emissiveIntensity: 0.1
              });
              const reflectionMesh = new THREE.Mesh(windowGeometry, reflectionMaterial);
              reflectionMesh.position.copy(windowMesh.position);
              reflectionMesh.position.z += side === 0 ? 0.01 : side === 2 ? -0.01 : 0;
              reflectionMesh.position.x += side === 1 ? 0.01 : side === 3 ? -0.01 : 0;
              buildingGroup.add(reflectionMesh);
            }
            
            buildingGroup.add(windowMesh);
            buildingGroup.add(frameMesh);
          }
        }
      }
      
      // 添加阳台装饰（住宅楼）
      if (building.type === 'residential') {
        for (let floor = 3; floor < building.floors; floor += 5) {
          const balconyGeometry = new THREE.BoxGeometry(9, 0.2, 1.5);
          const balconyMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
          const balconyMesh = new THREE.Mesh(balconyGeometry, balconyMaterial);
          balconyMesh.position.set(0, floor * 3, 5);
          buildingGroup.add(balconyMesh);
        }
      }
      
      // 楼宇顶部标识和天线
      const topGeometry = new THREE.CylinderGeometry(1, 1, 2, 8);
      const topMaterial = new THREE.MeshLambertMaterial({ 
        color: getBuildingTypeColor(building.type) 
      });
      const topMesh = new THREE.Mesh(topGeometry, topMaterial);
      topMesh.position.y = buildingHeight + 1;
      
      // 添加天线
      const antennaGeometry = new THREE.CylinderGeometry(0.1, 0.1, 8, 8);
      const antennaMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
      const antennaMesh = new THREE.Mesh(antennaGeometry, antennaMaterial);
      antennaMesh.position.y = buildingHeight + 6;
      
      // 天线顶部信号灯
      const signalGeometry = new THREE.SphereGeometry(0.3, 8, 8);
      const signalMaterial = new THREE.MeshLambertMaterial({ 
        color: building.status === 'normal' ? 0x00FF00 : 
               building.status === 'medium' ? 0xFFFF00 : 0xFF0000,
        emissive: building.status === 'normal' ? 0x004400 : 
                  building.status === 'medium' ? 0x444400 : 0x440000
      });
      const signalMesh = new THREE.Mesh(signalGeometry, signalMaterial);
      signalMesh.position.y = buildingHeight + 10;
      
      // 地基
      const baseGeometry = new THREE.CylinderGeometry(6, 6, 1, 16);
      const baseMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x424242,
        transparent: true,
        opacity: 0.6
      });
      const baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
      baseMesh.position.y = 0.5;
      
      // 地基装饰环
      const ringGeometry = new THREE.RingGeometry(6, 7, 16);
      const ringMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x666666,
        side: THREE.DoubleSide
      });
      const ringMesh = new THREE.Mesh(ringGeometry, ringMaterial);
      ringMesh.rotation.x = -Math.PI / 2;
      ringMesh.position.y = 1;
      
      // 添加楼宇入口装饰
      const entranceGeometry = new THREE.BoxGeometry(3, 4, 1);
      const entranceMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x8B4513,
        transparent: true,
        opacity: 0.8
      });
      const entranceMesh = new THREE.Mesh(entranceGeometry, entranceMaterial);
      entranceMesh.position.set(0, 2, 4.5);
      
      // 入口玻璃门
      const doorGlassGeometry = new THREE.PlaneGeometry(2.5, 3.5);
      const doorGlassMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x87CEEB,
        transparent: true,
        opacity: 0.3
      });
      const doorGlassMesh = new THREE.Mesh(doorGlassGeometry, doorGlassMaterial);
      doorGlassMesh.position.set(0, 2, 5.1);
      
      // 楼宇标识牌
      const signGeometry = new THREE.PlaneGeometry(4, 1);
      const signMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x2F4F4F,
        side: THREE.DoubleSide
      });
      const signMesh = new THREE.Mesh(signGeometry, signMaterial);
      signMesh.position.set(0, 6, 4.5);
      
      // 屋顶装饰
      const roofDecoGeometry = new THREE.ConeGeometry(2, 3, 8);
      const roofDecoMaterial = new THREE.MeshLambertMaterial({ 
        color: getBuildingTypeColor(building.type),
        emissive: getBuildingTypeColor(building.type),
        emissiveIntensity: 0.1
      });
      const roofDecoMesh = new THREE.Mesh(roofDecoGeometry, roofDecoMaterial);
      roofDecoMesh.position.y = buildingHeight + 4;

      buildingGroup.add(topMesh);
      buildingGroup.add(antennaMesh);
      buildingGroup.add(signalMesh);
      buildingGroup.add(baseMesh);
      buildingGroup.add(ringMesh);
      buildingGroup.add(entranceMesh);
      buildingGroup.add(doorGlassMesh);
      buildingGroup.add(signMesh);
      buildingGroup.add(roofDecoMesh);
      
      // 添加空调外机装饰
      for (let floor = 2; floor < building.floors; floor += 3) {
        for (let side = 0; side < 4; side++) {
          if (Math.random() > 0.6) { // 随机分布空调外机
            const acGeometry = new THREE.BoxGeometry(0.8, 0.6, 0.4);
            const acMaterial = new THREE.MeshLambertMaterial({ color: 0xC0C0C0 });
            const acMesh = new THREE.Mesh(acGeometry, acMaterial);
            
            const acY = floor * 3 - 1;
            const acOffset = (Math.random() - 0.5) * 4;
            
            if (side === 0) { // 前面
              acMesh.position.set(acOffset, acY, 4.5);
            } else if (side === 1) { // 右面
              acMesh.position.set(4.5, acY, acOffset);
            } else if (side === 2) { // 后面
              acMesh.position.set(acOffset, acY, -4.5);
            } else { // 左面
              acMesh.position.set(-4.5, acY, acOffset);
            }
            
            // 空调外机风扇
            const fanGeometry = new THREE.CylinderGeometry(0.2, 0.2, 0.1, 8);
            const fanMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
            const fanMesh = new THREE.Mesh(fanGeometry, fanMaterial);
            fanMesh.position.copy(acMesh.position);
            fanMesh.position.y += 0.35;
            fanMesh.rotation.x = Math.PI / 2;
            
            buildingGroup.add(acMesh);
            buildingGroup.add(fanMesh);
          }
        }
      }
      
      // 添加广告牌装饰（商业建筑）
      if (building.type === 'commercial') {
        const billboardGeometry = new THREE.PlaneGeometry(6, 3);
        const billboardMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFF6B6B,
          transparent: true,
          opacity: 0.9
        });
        const billboardMesh = new THREE.Mesh(billboardGeometry, billboardMaterial);
        billboardMesh.position.set(0, buildingHeight - 5, 4.2);
        
        // 广告牌边框
        const billboardFrameGeometry = new THREE.PlaneGeometry(6.2, 3.2);
        const billboardFrameMaterial = new THREE.MeshLambertMaterial({ 
          color: 0x333333,
          side: THREE.DoubleSide
        });
        const billboardFrameMesh = new THREE.Mesh(billboardFrameGeometry, billboardFrameMaterial);
        billboardFrameMesh.position.set(0, buildingHeight - 5, 4.15);
        
        // 广告牌灯光
        const lightGeometry = new THREE.SphereGeometry(0.1, 8, 8);
        const lightMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFFFFFF,
          emissive: 0xFFFFFF,
          emissiveIntensity: 0.3
        });
        
        for (let i = 0; i < 4; i++) {
          const lightMesh = new THREE.Mesh(lightGeometry, lightMaterial);
          lightMesh.position.set((i - 1.5) * 2, buildingHeight - 3.5, 4.3);
          buildingGroup.add(lightMesh);
        }
        
        buildingGroup.add(billboardFrameMesh);
        buildingGroup.add(billboardMesh);
      }
      
      // 添加卫星天线（办公楼）
      if (building.type === 'office') {
        const dishGeometry = new THREE.SphereGeometry(1.5, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2);
        const dishMaterial = new THREE.MeshLambertMaterial({ color: 0xE0E0E0 });
        const dishMesh = new THREE.Mesh(dishGeometry, dishMaterial);
        dishMesh.position.set(2, buildingHeight + 2, 2);
        dishMesh.rotation.x = -Math.PI / 4;
        
        // 天线支架
        const supportGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 8);
        const supportMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const supportMesh = new THREE.Mesh(supportGeometry, supportMaterial);
        supportMesh.position.set(2, buildingHeight + 0.5, 2);
        
        buildingGroup.add(dishMesh);
        buildingGroup.add(supportMesh);
      }
      
      // 添加太阳能板（绿色建筑）
      if (building.type === 'mixed' || Math.random() > 0.7) {
        for (let i = 0; i < 3; i++) {
          const solarGeometry = new THREE.PlaneGeometry(2, 1);
          const solarMaterial = new THREE.MeshLambertMaterial({ 
            color: 0x1E3A8A,
            transparent: true,
            opacity: 0.8
          });
          const solarMesh = new THREE.Mesh(solarGeometry, solarMaterial);
          solarMesh.position.set((i - 1) * 2.5, buildingHeight + 0.1, 0);
          solarMesh.rotation.x = -Math.PI / 2;
          solarMesh.rotation.z = Math.PI / 8;
          
          // 太阳能板框架
          const frameGeometry = new THREE.PlaneGeometry(2.1, 1.1);
          const frameMaterial = new THREE.MeshLambertMaterial({ 
            color: 0x333333,
            side: THREE.DoubleSide
          });
          const frameMesh = new THREE.Mesh(frameGeometry, frameMaterial);
          frameMesh.position.copy(solarMesh.position);
          frameMesh.position.y -= 0.01;
          frameMesh.rotation.copy(solarMesh.rotation);
          
          buildingGroup.add(frameMesh);
          buildingGroup.add(solarMesh);
        }
      }
      
      // 添加电梯
      building.elevators.forEach((elevator: ElevatorData, index: number) => {
        const elevatorGroup = createElevator(elevator, buildingHeight);
        const elevatorX = (index - building.elevators.length / 2) * 2;
        const elevatorZ = 5;
        elevatorGroup.position.set(elevatorX, 0, elevatorZ);
        elevatorGroup.userData.building = building;
        
        // 设置电梯用户数据用于点击检测
        elevatorGroup.userData = { 
          type: 'elevator',
          elevator: elevator,
          building: building,
          deviceInfo: mockDevicesDataPhase1.find(device => 
            device.name.includes(elevator.id) || 
            device.id.includes(elevator.id.replace(/[^0-9]/g, ''))
          )
        };
        buildingGroup.add(elevatorGroup);
      });

      // 为建筑物中的设备添加信息标签
      const buildingDevices = mockDevicesDataPhase1.filter(device => device.buildingId === building.id);
      buildingDevices.forEach((device, index) => {
        // 设备位置（在建筑物周围分布）
        const deviceAngle = (index / buildingDevices.length) * Math.PI * 2;
        const deviceDistance = 6;
        const deviceX = Math.cos(deviceAngle) * deviceDistance;
        const deviceZ = Math.sin(deviceAngle) * deviceDistance;
        const deviceY = Math.random() * buildingHeight * 0.8 + 2;

        // 创建设备指示器
         const deviceGeometry = new THREE.SphereGeometry(0.3, 8, 6);
         const deviceMaterial = new THREE.MeshLambertMaterial({ 
           color: device.status === 'online' ? 0x00FF00 : 
                  device.status === 'maintenance' ? 0xFFFF00 : 0xFF0000,
           emissive: device.status === 'online' ? 0x004400 : 
                     device.status === 'maintenance' ? 0x444400 : 0x440000
         });
        const deviceMesh = new THREE.Mesh(deviceGeometry, deviceMaterial);
        deviceMesh.position.set(deviceX, deviceY, deviceZ);
        
        // 设备连接线
        const lineGeometry = new THREE.BufferGeometry().setFromPoints([
          new THREE.Vector3(0, buildingHeight / 2, 0),
          new THREE.Vector3(deviceX, deviceY, deviceZ)
        ]);
        const lineMaterial = new THREE.LineBasicMaterial({ 
          color: 0x666666,
          transparent: true,
          opacity: 0.5
        });
        const deviceLine = new THREE.Line(lineGeometry, lineMaterial);
        
        // 创建3D设备图标
        const deviceIcon = createDeviceIcon(device);
        deviceIcon.position.set(deviceX, deviceY, deviceZ);
        
        // 设置设备用户数据用于点击检测
        deviceMesh.userData = {
          type: 'device',
          device: device,
          building: building
        };
        deviceIcon.userData = {
          type: 'device',
          device: device,
          building: building
        };
        
        buildingGroup.add(deviceMesh);
        buildingGroup.add(deviceLine);
        buildingGroup.add(deviceIcon);
      });
      
      // 添加楼宇周围绿化装饰
      const landscapeGroup = new THREE.Group();
      
      // 添加树木
      for (let i = 0; i < 4; i++) {
        const treeAngle = (i / 4) * Math.PI * 2;
        const treeDistance = 12 + Math.random() * 5;
        const treeX = Math.cos(treeAngle) * treeDistance;
        const treeZ = Math.sin(treeAngle) * treeDistance;
        
        // 树干
        const trunkGeometry = new THREE.CylinderGeometry(0.3, 0.5, 4, 8);
        const trunkMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
        const trunkMesh = new THREE.Mesh(trunkGeometry, trunkMaterial);
        trunkMesh.position.set(treeX, 2, treeZ);
        
        // 树冠
        const crownGeometry = new THREE.SphereGeometry(2.5, 8, 6);
        const crownMaterial = new THREE.MeshLambertMaterial({ color: 0x228B22 });
        const crownMesh = new THREE.Mesh(crownGeometry, crownMaterial);
        crownMesh.position.set(treeX, 5.5, treeZ);
        
        landscapeGroup.add(trunkMesh);
        landscapeGroup.add(crownMesh);
      }
      
      // 添加花坛
      for (let i = 0; i < 6; i++) {
        const flowerAngle = (i / 6) * Math.PI * 2;
        const flowerDistance = 8;
        const flowerX = Math.cos(flowerAngle) * flowerDistance;
        const flowerZ = Math.sin(flowerAngle) * flowerDistance;
        
        // 花坛底座
        const planterGeometry = new THREE.CylinderGeometry(1.5, 1.5, 0.5, 8);
        const planterMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
        const planterMesh = new THREE.Mesh(planterGeometry, planterMaterial);
        planterMesh.position.set(flowerX, 0.25, flowerZ);
        
        // 花朵
        const flowerColors = [0xFF69B4, 0xFF6347, 0xFFD700, 0x9370DB, 0x00CED1];
        for (let j = 0; j < 5; j++) {
          const flowerGeometry = new THREE.SphereGeometry(0.2, 6, 4);
          const flowerMaterial = new THREE.MeshLambertMaterial({ 
            color: flowerColors[j % flowerColors.length] 
          });
          const flowerMesh = new THREE.Mesh(flowerGeometry, flowerMaterial);
          const flowerOffsetX = (Math.random() - 0.5) * 2;
          const flowerOffsetZ = (Math.random() - 0.5) * 2;
          flowerMesh.position.set(
            flowerX + flowerOffsetX, 
            0.7 + Math.random() * 0.5, 
            flowerZ + flowerOffsetZ
          );
          landscapeGroup.add(flowerMesh);
        }
        
        landscapeGroup.add(planterMesh);
      }
      
      // 添加路灯
      for (let i = 0; i < 8; i++) {
        const lampAngle = (i / 8) * Math.PI * 2;
        const lampDistance = 20;
        const lampX = Math.cos(lampAngle) * lampDistance;
        const lampZ = Math.sin(lampAngle) * lampDistance;
        
        // 路灯杆
        const poleGeometry = new THREE.CylinderGeometry(0.1, 0.15, 8, 8);
        const poleMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
        const poleMesh = new THREE.Mesh(poleGeometry, poleMaterial);
        poleMesh.position.set(lampX, 4, lampZ);
        
        // 路灯头
        const lampGeometry = new THREE.SphereGeometry(0.5, 8, 6);
        const lampMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFFFFE0,
          emissive: 0xFFFFE0,
          emissiveIntensity: 0.2
        });
        const lampMesh = new THREE.Mesh(lampGeometry, lampMaterial);
        lampMesh.position.set(lampX, 8.5, lampZ);
        
        // 路灯底座
        const baseGeometry = new THREE.CylinderGeometry(0.5, 0.5, 0.5, 8);
        const baseMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
        baseMesh.position.set(lampX, 0.25, lampZ);
        
        landscapeGroup.add(poleMesh);
        landscapeGroup.add(lampMesh);
        landscapeGroup.add(baseMesh);
      }
      
      // 添加小径
      const pathGeometry = new THREE.RingGeometry(10, 11, 32);
      const pathMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x8B7355,
        side: THREE.DoubleSide
      });
      const pathMesh = new THREE.Mesh(pathGeometry, pathMaterial);
      pathMesh.rotation.x = -Math.PI / 2;
      pathMesh.position.y = 0.01;
      landscapeGroup.add(pathMesh);
      
      // 添加装饰石块
      for (let i = 0; i < 12; i++) {
        const rockAngle = (i / 12) * Math.PI * 2;
        const rockDistance = 15 + Math.random() * 3;
        const rockX = Math.cos(rockAngle) * rockDistance;
        const rockZ = Math.sin(rockAngle) * rockDistance;
        
        const rockGeometry = new THREE.DodecahedronGeometry(0.5 + Math.random() * 0.5);
        const rockMaterial = new THREE.MeshLambertMaterial({ color: 0x696969 });
        const rockMesh = new THREE.Mesh(rockGeometry, rockMaterial);
        rockMesh.position.set(rockX, 0.3, rockZ);
        rockMesh.rotation.set(
          Math.random() * Math.PI,
          Math.random() * Math.PI,
          Math.random() * Math.PI
        );
        landscapeGroup.add(rockMesh);
      }
      
      buildingGroup.add(landscapeGroup);
      buildingGroup.position.set(building.position.x, building.position.y, building.position.z);
      buildingGroup.userData = { building };
      scene.add(buildingGroup);
    });

    // 创建马路系统
    const createRoadSystem = () => {
      const roadGroup = new THREE.Group();
      
      // 马路材质
      const roadMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x2C2C2C,
        transparent: true,
        opacity: 0.9
      });
      
      const sidewalkMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x8B8B8B,
        transparent: true,
        opacity: 0.8
      });
      
      const lineMaterial = new THREE.MeshLambertMaterial({ 
        color: 0xFFFFFF,
        transparent: true,
        opacity: 0.9
      });
      
      const crosswalkMaterial = new THREE.MeshLambertMaterial({ 
        color: 0xFFFFFF,
        transparent: true,
        opacity: 0.8
      });
      
      // 主干道 - 横向
      const mainRoadGeometry = new THREE.PlaneGeometry(80, 8);
      const mainRoadMesh = new THREE.Mesh(mainRoadGeometry, roadMaterial);
      mainRoadMesh.rotation.x = -Math.PI / 2;
      mainRoadMesh.position.set(0, 0.02, 0);
      roadGroup.add(mainRoadMesh);
      
      // 主干道 - 纵向
      const mainRoadVerticalGeometry = new THREE.PlaneGeometry(8, 80);
      const mainRoadVerticalMesh = new THREE.Mesh(mainRoadVerticalGeometry, roadMaterial);
      mainRoadVerticalMesh.rotation.x = -Math.PI / 2;
      mainRoadVerticalMesh.position.set(0, 0.02, 0);
      roadGroup.add(mainRoadVerticalMesh);
      
      // 支路
      for (let i = -2; i <= 2; i++) {
        if (i !== 0) {
          // 横向支路
          const sideRoadGeometry = new THREE.PlaneGeometry(60, 4);
          const sideRoadMesh = new THREE.Mesh(sideRoadGeometry, roadMaterial);
          sideRoadMesh.rotation.x = -Math.PI / 2;
          sideRoadMesh.position.set(0, 0.01, i * 15);
          roadGroup.add(sideRoadMesh);
          
          // 纵向支路
          const sideRoadVerticalGeometry = new THREE.PlaneGeometry(4, 60);
          const sideRoadVerticalMesh = new THREE.Mesh(sideRoadVerticalGeometry, roadMaterial);
          sideRoadVerticalMesh.rotation.x = -Math.PI / 2;
          sideRoadVerticalMesh.position.set(i * 15, 0.01, 0);
          roadGroup.add(sideRoadVerticalMesh);
        }
      }
      
      // 人行道
      const sidewalkPositions = [
        { x: 0, z: 5, width: 80, height: 2 },   // 主干道北侧
        { x: 0, z: -5, width: 80, height: 2 },  // 主干道南侧
        { x: 5, z: 0, width: 2, height: 80 },   // 主干道东侧
        { x: -5, z: 0, width: 2, height: 80 }   // 主干道西侧
      ];
      
      sidewalkPositions.forEach(pos => {
        const sidewalkGeometry = new THREE.PlaneGeometry(pos.width, pos.height);
        const sidewalkMesh = new THREE.Mesh(sidewalkGeometry, sidewalkMaterial);
        sidewalkMesh.rotation.x = -Math.PI / 2;
        sidewalkMesh.position.set(pos.x, 0.03, pos.z);
        roadGroup.add(sidewalkMesh);
      });
      
      // 道路标线 - 中央分隔线
      for (let i = -40; i <= 40; i += 4) {
        const lineGeometry = new THREE.PlaneGeometry(2, 0.2);
        const lineMesh = new THREE.Mesh(lineGeometry, lineMaterial);
        lineMesh.rotation.x = -Math.PI / 2;
        lineMesh.position.set(i, 0.03, 0);
        roadGroup.add(lineMesh);
        
        // 纵向中央分隔线
        const lineVerticalGeometry = new THREE.PlaneGeometry(0.2, 2);
        const lineVerticalMesh = new THREE.Mesh(lineVerticalGeometry, lineMaterial);
        lineVerticalMesh.rotation.x = -Math.PI / 2;
        lineVerticalMesh.position.set(0, 0.03, i);
        roadGroup.add(lineVerticalMesh);
      }
      
      // 车道分隔线
      for (let i = -40; i <= 40; i += 6) {
        // 横向车道线
        const laneLineGeometry = new THREE.PlaneGeometry(1.5, 0.15);
        const laneLineMesh1 = new THREE.Mesh(laneLineGeometry, lineMaterial);
        laneLineMesh1.rotation.x = -Math.PI / 2;
        laneLineMesh1.position.set(i, 0.025, 2);
        roadGroup.add(laneLineMesh1);
        
        const laneLineMesh2 = new THREE.Mesh(laneLineGeometry, lineMaterial);
        laneLineMesh2.rotation.x = -Math.PI / 2;
        laneLineMesh2.position.set(i, 0.025, -2);
        roadGroup.add(laneLineMesh2);
        
        // 纵向车道线
        const laneLineVerticalGeometry = new THREE.PlaneGeometry(0.15, 1.5);
        const laneLineVerticalMesh1 = new THREE.Mesh(laneLineVerticalGeometry, lineMaterial);
        laneLineVerticalMesh1.rotation.x = -Math.PI / 2;
        laneLineVerticalMesh1.position.set(2, 0.025, i);
        roadGroup.add(laneLineVerticalMesh1);
        
        const laneLineVerticalMesh2 = new THREE.Mesh(laneLineVerticalGeometry, lineMaterial);
        laneLineVerticalMesh2.rotation.x = -Math.PI / 2;
        laneLineVerticalMesh2.position.set(-2, 0.025, i);
        roadGroup.add(laneLineVerticalMesh2);
      }
      
      // 斑马线
      const crosswalkPositions = [
        { x: 0, z: 8, rotation: 0 },
        { x: 0, z: -8, rotation: 0 },
        { x: 8, z: 0, rotation: Math.PI / 2 },
        { x: -8, z: 0, rotation: Math.PI / 2 }
      ];
      
      crosswalkPositions.forEach(pos => {
        for (let i = 0; i < 8; i++) {
          const crosswalkGeometry = new THREE.PlaneGeometry(0.8, 8);
          const crosswalkMesh = new THREE.Mesh(crosswalkGeometry, crosswalkMaterial);
          crosswalkMesh.rotation.x = -Math.PI / 2;
          crosswalkMesh.rotation.z = pos.rotation;
          
          if (pos.rotation === 0) {
            crosswalkMesh.position.set((i - 3.5) * 1, 0.04, pos.z);
          } else {
            crosswalkMesh.position.set(pos.x, 0.04, (i - 3.5) * 1);
          }
          
          roadGroup.add(crosswalkMesh);
        }
      });
      
      return roadGroup;
    };
    
    // 添加马路系统到场景
    const roadSystem = createRoadSystem();
    scene.add(roadSystem);

    // 创建马路装饰元素
    const createRoadDecorations = () => {
      const decorationGroup = new THREE.Group();
      
      // 路灯材质
      const streetLightPoleMaterial = new THREE.MeshLambertMaterial({ color: 0x444444 });
      const streetLightMaterial = new THREE.MeshLambertMaterial({ 
        color: 0xFFFFAA,
        emissive: 0xFFFFAA,
        emissiveIntensity: 0.3
      });
      
      // 红绿灯材质
      const trafficLightPoleMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
      const redLightMaterial = new THREE.MeshLambertMaterial({ 
        color: 0xFF0000,
        emissive: 0xFF0000,
        emissiveIntensity: 0.5
      });
      const yellowLightMaterial = new THREE.MeshLambertMaterial({ 
        color: 0xFFFF00,
        emissive: 0xFFFF00,
        emissiveIntensity: 0.3
      });
      const greenLightMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x00FF00,
        emissive: 0x00FF00,
        emissiveIntensity: 0.5
      });
      
      // 交通标志材质
      const signPoleMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
      const signMaterial = new THREE.MeshLambertMaterial({ 
        color: 0xFF4444,
        transparent: true,
        opacity: 0.9
      });
      
      // 护栏材质
      const barrierMaterial = new THREE.MeshLambertMaterial({ color: 0xCCCCCC });
      
      // 垃圾桶材质
      const trashCanMaterial = new THREE.MeshLambertMaterial({ color: 0x2E8B57 });
      
      // 公交站台材质
      const busStopMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x4169E1,
        transparent: true,
        opacity: 0.8
      });
      
      // 添加路灯
      const streetLightPositions = [
        { x: -35, z: 7 }, { x: -25, z: 7 }, { x: -15, z: 7 }, { x: -5, z: 7 },
        { x: 5, z: 7 }, { x: 15, z: 7 }, { x: 25, z: 7 }, { x: 35, z: 7 },
        { x: -35, z: -7 }, { x: -25, z: -7 }, { x: -15, z: -7 }, { x: -5, z: -7 },
        { x: 5, z: -7 }, { x: 15, z: -7 }, { x: 25, z: -7 }, { x: 35, z: -7 },
        { x: 7, z: -35 }, { x: 7, z: -25 }, { x: 7, z: -15 }, { x: 7, z: -5 },
        { x: 7, z: 5 }, { x: 7, z: 15 }, { x: 7, z: 25 }, { x: 7, z: 35 },
        { x: -7, z: -35 }, { x: -7, z: -25 }, { x: -7, z: -15 }, { x: -7, z: -5 },
        { x: -7, z: 5 }, { x: -7, z: 15 }, { x: -7, z: 25 }, { x: -7, z: 35 }
      ];
      
      streetLightPositions.forEach(pos => {
        // 路灯杆
        const poleGeometry = new THREE.CylinderGeometry(0.1, 0.15, 6, 8);
        const poleMesh = new THREE.Mesh(poleGeometry, streetLightPoleMaterial);
        poleMesh.position.set(pos.x, 3, pos.z);
        
        // 路灯头
        const lightGeometry = new THREE.SphereGeometry(0.4, 12, 8);
        const lightMesh = new THREE.Mesh(lightGeometry, streetLightMaterial);
        lightMesh.position.set(pos.x, 5.8, pos.z);
        
        // 路灯罩
        const lampShadeGeometry = new THREE.ConeGeometry(0.6, 0.8, 8);
        const lampShadeMaterial = new THREE.MeshLambertMaterial({ 
          color: 0x333333,
          transparent: true,
          opacity: 0.7
        });
        const lampShadeMesh = new THREE.Mesh(lampShadeGeometry, lampShadeMaterial);
        lampShadeMesh.position.set(pos.x, 6.2, pos.z);
        
        decorationGroup.add(poleMesh);
        decorationGroup.add(lightMesh);
        decorationGroup.add(lampShadeMesh);
      });
      
      // 添加红绿灯
      const trafficLightPositions = [
        { x: 6, z: 6 }, { x: -6, z: 6 }, { x: 6, z: -6 }, { x: -6, z: -6 }
      ];
      
      trafficLightPositions.forEach(pos => {
        // 红绿灯杆
        const poleGeometry = new THREE.CylinderGeometry(0.15, 0.15, 8, 8);
        const poleMesh = new THREE.Mesh(poleGeometry, trafficLightPoleMaterial);
        poleMesh.position.set(pos.x, 4, pos.z);
        
        // 红绿灯盒子
        const boxGeometry = new THREE.BoxGeometry(0.8, 2.4, 0.4);
        const boxMaterial = new THREE.MeshLambertMaterial({ color: 0x222222 });
        const boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);
        boxMesh.position.set(pos.x, 7, pos.z);
        
        // 红灯
        const redLightGeometry = new THREE.CircleGeometry(0.25, 16);
        const redLightMesh = new THREE.Mesh(redLightGeometry, redLightMaterial);
        redLightMesh.position.set(pos.x, 7.6, pos.z + 0.21);
        
        // 黄灯
        const yellowLightGeometry = new THREE.CircleGeometry(0.25, 16);
        const yellowLightMesh = new THREE.Mesh(yellowLightGeometry, yellowLightMaterial);
        yellowLightMesh.position.set(pos.x, 7, pos.z + 0.21);
        
        // 绿灯
        const greenLightGeometry = new THREE.CircleGeometry(0.25, 16);
        const greenLightMesh = new THREE.Mesh(greenLightGeometry, greenLightMaterial);
        greenLightMesh.position.set(pos.x, 6.4, pos.z + 0.21);
        
        decorationGroup.add(poleMesh);
        decorationGroup.add(boxMesh);
        decorationGroup.add(redLightMesh);
        decorationGroup.add(yellowLightMesh);
        decorationGroup.add(greenLightMesh);
      });
      
      // 添加交通标志
      const signPositions = [
        { x: 10, z: 8, type: 'stop' },
        { x: -10, z: 8, type: 'yield' },
        { x: 8, z: 10, type: 'speed' },
        { x: 8, z: -10, type: 'parking' },
        { x: -8, z: 10, type: 'no_entry' },
        { x: -8, z: -10, type: 'one_way' }
      ];
      
      signPositions.forEach(pos => {
        // 标志杆
        const poleGeometry = new THREE.CylinderGeometry(0.08, 0.08, 3, 8);
        const poleMesh = new THREE.Mesh(poleGeometry, signPoleMaterial);
        poleMesh.position.set(pos.x, 1.5, pos.z);
        
        // 标志牌
        const signGeometry = pos.type === 'stop' ? 
          new THREE.OctahedronGeometry(0.8) : 
          new THREE.CircleGeometry(0.6, 16);
        const signMesh = new THREE.Mesh(signGeometry, signMaterial);
        signMesh.position.set(pos.x, 2.8, pos.z);
        
        decorationGroup.add(poleMesh);
        decorationGroup.add(signMesh);
      });
      
      // 添加护栏
      for (let i = -35; i <= 35; i += 2) {
        // 主干道护栏
        if (Math.abs(i) > 8) {
          const barrierGeometry = new THREE.BoxGeometry(1.8, 1, 0.1);
          const barrierMesh1 = new THREE.Mesh(barrierGeometry, barrierMaterial);
          barrierMesh1.position.set(i, 0.5, 4.5);
          decorationGroup.add(barrierMesh1);
          
          const barrierMesh2 = new THREE.Mesh(barrierGeometry, barrierMaterial);
          barrierMesh2.position.set(i, 0.5, -4.5);
          decorationGroup.add(barrierMesh2);
          
          // 纵向护栏
          const barrierVerticalGeometry = new THREE.BoxGeometry(0.1, 1, 1.8);
          const barrierVerticalMesh1 = new THREE.Mesh(barrierVerticalGeometry, barrierMaterial);
          barrierVerticalMesh1.position.set(4.5, 0.5, i);
          decorationGroup.add(barrierVerticalMesh1);
          
          const barrierVerticalMesh2 = new THREE.Mesh(barrierVerticalGeometry, barrierMaterial);
          barrierVerticalMesh2.position.set(-4.5, 0.5, i);
          decorationGroup.add(barrierVerticalMesh2);
        }
      }
      
      // 添加垃圾桶
      const trashCanPositions = [
        { x: 12, z: 8 }, { x: -12, z: 8 }, { x: 12, z: -8 }, { x: -12, z: -8 },
        { x: 8, z: 12 }, { x: 8, z: -12 }, { x: -8, z: 12 }, { x: -8, z: -12 }
      ];
      
      trashCanPositions.forEach(pos => {
        const trashCanGeometry = new THREE.CylinderGeometry(0.4, 0.5, 1.2, 12);
        const trashCanMesh = new THREE.Mesh(trashCanGeometry, trashCanMaterial);
        trashCanMesh.position.set(pos.x, 0.6, pos.z);
        
        // 垃圾桶盖
        const lidGeometry = new THREE.CylinderGeometry(0.45, 0.45, 0.1, 12);
        const lidMaterial = new THREE.MeshLambertMaterial({ color: 0x1F4F1F });
        const lidMesh = new THREE.Mesh(lidGeometry, lidMaterial);
        lidMesh.position.set(pos.x, 1.25, pos.z);
        
        decorationGroup.add(trashCanMesh);
        decorationGroup.add(lidMesh);
      });
      
      // 添加公交站台
      const busStopPositions = [
        { x: 20, z: 8 }, { x: -20, z: 8 }, { x: 8, z: 20 }, { x: 8, z: -20 }
      ];
      
      busStopPositions.forEach(pos => {
        // 站台顶棚
        const roofGeometry = new THREE.BoxGeometry(6, 0.2, 3);
        const roofMesh = new THREE.Mesh(roofGeometry, busStopMaterial);
        roofMesh.position.set(pos.x, 3, pos.z);
        
        // 支柱
        for (let i = 0; i < 4; i++) {
          const pillarGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 8);
          const pillarMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
          const pillarMesh = new THREE.Mesh(pillarGeometry, pillarMaterial);
          const pillarX = pos.x + (i % 2 === 0 ? -2.5 : 2.5);
          const pillarZ = pos.z + (i < 2 ? -1 : 1);
          pillarMesh.position.set(pillarX, 1.5, pillarZ);
          decorationGroup.add(pillarMesh);
        }
        
        // 座椅
        const benchGeometry = new THREE.BoxGeometry(4, 0.3, 0.8);
        const benchMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
        const benchMesh = new THREE.Mesh(benchGeometry, benchMaterial);
        benchMesh.position.set(pos.x, 0.4, pos.z - 0.8);
        
        // 站牌
        const signBoardGeometry = new THREE.PlaneGeometry(1.5, 2);
        const signBoardMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFFFFFF,
          transparent: true,
          opacity: 0.9
        });
        const signBoardMesh = new THREE.Mesh(signBoardGeometry, signBoardMaterial);
        signBoardMesh.position.set(pos.x + 2.8, 1.5, pos.z);
        signBoardMesh.rotation.y = pos.x > 0 ? Math.PI : 0;
        
        decorationGroup.add(roofMesh);
        decorationGroup.add(benchMesh);
        decorationGroup.add(signBoardMesh);
      });
      
      // 创建车辆模型函数
      const createVehicle = (type: 'car' | 'suv' | 'truck' | 'bus', color: number) => {
        const vehicleGroup = new THREE.Group();
        
        // 车身材质
        const bodyMaterial = new THREE.MeshLambertMaterial({ color });
        const windowMaterial = new THREE.MeshLambertMaterial({ 
          color: 0x87CEEB, 
          transparent: true, 
          opacity: 0.7 
        });
        const tireMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
        const rimMaterial = new THREE.MeshLambertMaterial({ color: 0xC0C0C0 });
        
        let bodyGeometry, windowGeometry, bodyHeight, bodyWidth, bodyLength;
        
        switch (type) {
          case 'car':
            // 轿车
            bodyLength = 4;
            bodyWidth = 1.8;
            bodyHeight = 1.2;
            bodyGeometry = new THREE.BoxGeometry(bodyLength, bodyHeight, bodyWidth);
            windowGeometry = new THREE.BoxGeometry(bodyLength * 0.6, bodyHeight * 0.4, bodyWidth * 0.9);
            break;
            
          case 'suv':
            // SUV
            bodyLength = 4.5;
            bodyWidth = 2;
            bodyHeight = 1.8;
            bodyGeometry = new THREE.BoxGeometry(bodyLength, bodyHeight, bodyWidth);
            windowGeometry = new THREE.BoxGeometry(bodyLength * 0.6, bodyHeight * 0.3, bodyWidth * 0.9);
            break;
            
          case 'truck':
            // 卡车
            bodyLength = 6;
            bodyWidth = 2.2;
            bodyHeight = 2.5;
            bodyGeometry = new THREE.BoxGeometry(bodyLength, bodyHeight, bodyWidth);
            windowGeometry = new THREE.BoxGeometry(bodyLength * 0.25, bodyHeight * 0.3, bodyWidth * 0.9);
            break;
            
          case 'bus':
            // 公交车
            bodyLength = 8;
            bodyWidth = 2.5;
            bodyHeight = 2.8;
            bodyGeometry = new THREE.BoxGeometry(bodyLength, bodyHeight, bodyWidth);
            windowGeometry = new THREE.BoxGeometry(bodyLength * 0.8, bodyHeight * 0.25, bodyWidth * 0.9);
            break;
        }
        
        // 车身
        const bodyMesh = new THREE.Mesh(bodyGeometry, bodyMaterial);
        bodyMesh.position.y = bodyHeight / 2 + 0.3;
        vehicleGroup.add(bodyMesh);
        
        // 车窗
        const windowMesh = new THREE.Mesh(windowGeometry, windowMaterial);
        windowMesh.position.y = bodyHeight * 0.8 + 0.3;
        vehicleGroup.add(windowMesh);
        
        // 车轮位置
        const wheelPositions = [
          { x: bodyLength * 0.3, z: bodyWidth * 0.4 },
          { x: bodyLength * 0.3, z: -bodyWidth * 0.4 },
          { x: -bodyLength * 0.3, z: bodyWidth * 0.4 },
          { x: -bodyLength * 0.3, z: -bodyWidth * 0.4 }
        ];
        
        // 添加车轮
        wheelPositions.forEach(pos => {
          // 轮胎
          const tireGeometry = new THREE.CylinderGeometry(0.4, 0.4, 0.3, 16);
          const tireMesh = new THREE.Mesh(tireGeometry, tireMaterial);
          tireMesh.rotation.z = Math.PI / 2;
          tireMesh.position.set(pos.x, 0.4, pos.z);
          
          // 轮毂
          const rimGeometry = new THREE.CylinderGeometry(0.25, 0.25, 0.35, 16);
          const rimMesh = new THREE.Mesh(rimGeometry, rimMaterial);
          rimMesh.rotation.z = Math.PI / 2;
          rimMesh.position.set(pos.x, 0.4, pos.z);
          
          vehicleGroup.add(tireMesh);
          vehicleGroup.add(rimMesh);
        });
        
        // 车灯
        const headlightMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFFFFFF,
          emissive: 0xFFFFFF,
          emissiveIntensity: 0.3
        });
        
        const headlightGeometry = new THREE.SphereGeometry(0.15, 8, 8);
        const headlight1 = new THREE.Mesh(headlightGeometry, headlightMaterial);
        headlight1.position.set(bodyLength / 2 + 0.1, bodyHeight * 0.4 + 0.3, bodyWidth * 0.3);
        const headlight2 = new THREE.Mesh(headlightGeometry, headlightMaterial);
        headlight2.position.set(bodyLength / 2 + 0.1, bodyHeight * 0.4 + 0.3, -bodyWidth * 0.3);
        
        vehicleGroup.add(headlight1);
        vehicleGroup.add(headlight2);
        
        return vehicleGroup;
      };
      
      // 添加车辆到马路上
      const vehiclePositions = [
        // 主干道上的车辆
        { x: -25, z: 2, rotation: 0, type: 'car' as const, color: 0xFF4444 },
        { x: -15, z: -2, rotation: Math.PI, type: 'suv' as const, color: 0x4444FF },
        { x: 15, z: 2, rotation: 0, type: 'car' as const, color: 0x44FF44 },
        { x: 25, z: -2, rotation: Math.PI, type: 'truck' as const, color: 0xFFFF44 },
        
        // 纵向道路上的车辆
        { x: 2, z: -25, rotation: Math.PI / 2, type: 'car' as const, color: 0xFF44FF },
        { x: -2, z: -15, rotation: -Math.PI / 2, type: 'suv' as const, color: 0x44FFFF },
        { x: 2, z: 15, rotation: Math.PI / 2, type: 'bus' as const, color: 0xFFA500 },
        { x: -2, z: 25, rotation: -Math.PI / 2, type: 'car' as const, color: 0x8A2BE2 },
        
        // 支路上的车辆
        { x: -20, z: 17, rotation: 0, type: 'car' as const, color: 0x20B2AA },
        { x: 20, z: -17, rotation: Math.PI, type: 'suv' as const, color: 0xDC143C },
        { x: 17, z: 20, rotation: Math.PI / 2, type: 'car' as const, color: 0x32CD32 },
        { x: -17, z: -20, rotation: -Math.PI / 2, type: 'truck' as const, color: 0x4169E1 }
      ];
      
      vehiclePositions.forEach(pos => {
        const vehicle = createVehicle(pos.type, pos.color);
        vehicle.position.set(pos.x, 0, pos.z);
        vehicle.rotation.y = pos.rotation;
        decorationGroup.add(vehicle);
      });
      
      return decorationGroup;
    };
    
    // 添加马路装饰元素到场景
    const roadDecorations = createRoadDecorations();
    scene.add(roadDecorations);

    // 设置轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.enableZoom = true;
    controls.enableRotate = true;
    controls.enablePan = true;
    controlsRef.current = controls;

    // 点击检测
    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();

    const onMouseClick = (event: MouseEvent) => {
      const rect = currentMount.getBoundingClientRect();
      mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
      mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);
      const intersects = raycaster.intersectObjects(scene.children, true);

      if (intersects.length > 0) {
        const intersectedObject = intersects[0].object;
        let parent = intersectedObject.parent;
        
        // 检查是否点击了设备图标
        let deviceParent = parent;
        while (deviceParent && !deviceParent.userData.device) {
          deviceParent = deviceParent.parent;
        }
        
        // 检查是否点击了电梯
        let elevatorParent = parent;
        while (elevatorParent && !elevatorParent.userData.elevator) {
          elevatorParent = elevatorParent.parent;
        }
        
        // 检查是否点击了楼宇
        let buildingParent = parent;
        while (buildingParent && !buildingParent.userData.building) {
          buildingParent = buildingParent.parent;
        }
        
        // 优先检测设备图标点击
        if (deviceParent && deviceParent.userData.device) {
          const device = deviceParent.userData.device;
          setSelectedDevice(device);
          setDeviceModalVisible(true);
        } else if (elevatorParent && elevatorParent.userData.elevator) {
          const elevator = elevatorParent.userData.elevator;
          const deviceInfo = mockDevicesDataPhase1.find(device => 
            device.name.includes(elevator.id) || 
            device.id.includes(elevator.id.replace(/[^0-9]/g, ''))
          );
          
          if (deviceInfo) {
            setSelectedDevice(deviceInfo);
            setDeviceModalVisible(true);
          }
        } else if (buildingParent && buildingParent.userData.building && !elevatorParent && !deviceParent) {
          const building = buildingParent.userData.building;
          setSelectedBuilding(building);
          setBuildingModalVisible(true);
        }
      }
    };

    currentMount.addEventListener('click', onMouseClick);
    currentMount.appendChild(renderer.domElement);

    // 电梯动画函数
    const animateElevators = () => {
      scene.traverse((object) => {
        if (object.userData && object.userData.elevator && object.userData.carGroup) {
          const userData = object.userData;
          const carGroup = userData.carGroup;
          const buildingHeight = userData.buildingHeight;
          const currentTime = Date.now();
          
          // 每隔3-8秒随机改变目标楼层
          if (currentTime - userData.lastMoveTime > Math.random() * 5000 + 3000) {
            if (!userData.isMoving) {
              const maxFloor = Math.floor(buildingHeight / 3); // 假设每层3米高
              userData.targetFloor = Math.floor(Math.random() * maxFloor) + 1;
              userData.lastMoveTime = currentTime;
              
              if (userData.targetFloor !== userData.currentFloor) {
                userData.isMoving = true;
                userData.direction = userData.targetFloor > userData.currentFloor ? 1 : -1;
              }
            }
          }
          
          // 电梯运动逻辑
          if (userData.isMoving) {
            const targetY = (userData.targetFloor - 1) * 3 + 2.5; // 每层3米，轿厢高度2.5米
            const currentY = carGroup.position.y;
            const distance = Math.abs(targetY - currentY);
            
            if (distance > 0.1) {
              // 继续移动
              carGroup.position.y += userData.direction * userData.moveSpeed * 60; // 60fps假设
              
              // 限制移动范围
              const minY = 2.5; // 底层
              const maxY = buildingHeight - 2.5; // 顶层
              carGroup.position.y = Math.max(minY, Math.min(maxY, carGroup.position.y));
            } else {
              // 到达目标楼层
              carGroup.position.y = targetY;
              userData.currentFloor = userData.targetFloor;
              userData.isMoving = false;
              userData.lastMoveTime = currentTime;
            }
          }
        }
      });
    };

    // 动画循环（可见性感知，安全启动）
    const startLoop = () => {
      const animate = () => {
        if (document.hidden) {
          animationIdRef.current = undefined;
          return;
        }
        animationIdRef.current = requestAnimationFrame(animate);
        controls.update();
        animateElevators(); // 更新电梯动画
        renderer.render(scene, camera);
      };
      animate();
    };
    startLoopRef.current = startLoop;
    startLoop();

    // 页面可见性变化时控制动画循环
    const onVisibilityChange = () => {
      if (!document.hidden && !animationIdRef.current && startLoopRef.current) {
        startLoopRef.current();
      } else if (document.hidden && animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current);
        animationIdRef.current = undefined;
      }
    };
    document.addEventListener('visibilitychange', onVisibilityChange);
    setIsLoading(false);

    // 窗口大小变化处理
    const handleResize = () => {
      if (camera && renderer && currentMount) {
        camera.aspect = currentMount.clientWidth / currentMount.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(currentMount.clientWidth, currentMount.clientHeight);
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      if (animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current);
        animationIdRef.current = undefined;
      }
      document.removeEventListener('visibilitychange', onVisibilityChange);
      window.removeEventListener('resize', handleResize);
      currentMount.removeEventListener('click', onMouseClick);
    };
  }, [getBuildingColor, getBuildingTypeColor, createElevator]);

  useEffect(() => {
    if (!mountRef.current) return;

    const currentMount = mountRef.current;
    
    // 清理之前的场景
    if (animationIdRef.current) {
      cancelAnimationFrame(animationIdRef.current);
      animationIdRef.current = undefined;
    }
    
    if (controlsRef.current) {
      controlsRef.current.dispose();
      controlsRef.current = null;
    }
    
    if (rendererRef.current && currentMount) {
      try {
        currentMount.removeChild(rendererRef.current.domElement);
      } catch (e) {
        // 忽略DOM元素不存在的错误
      }
      rendererRef.current.dispose();
      rendererRef.current = null;
    }
    
    if (sceneRef.current) {
      const clearScene = (object: THREE.Object3D) => {
        while (object.children.length > 0) {
          const child = object.children[0];
          clearScene(child);
          object.remove(child);

          if (child instanceof THREE.Mesh) {
            if (child.geometry) child.geometry.dispose();
            if (child.material) {
              const disposeMaterial = (material: any) => {
                try {
                  const textureKeys = [
                    'map','lightMap','aoMap','emissiveMap','bumpMap','normalMap',
                    'displacementMap','roughnessMap','metalnessMap','alphaMap','envMap','gradientMap'
                  ];
                  textureKeys.forEach((key) => {
                    const tex = material && material[key];
                    if (tex && tex instanceof THREE.Texture) {
                      tex.dispose();
                    }
                  });
                } catch {}
                material.dispose && material.dispose();
              };
              if (Array.isArray(child.material)) {
                child.material.forEach(disposeMaterial);
              } else {
                disposeMaterial(child.material as any);
              }
            }
          }
        }
      };
      clearScene(sceneRef.current);
      sceneRef.current = null;
    }
    
    // 初始化场景
    const cleanup = initScene();

    return () => {
      if (animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current);
      }
      if (controlsRef.current) {
        controlsRef.current.dispose();
        controlsRef.current = null;
      }
      if (cleanup) cleanup();
    };
  }, [initScene]);

  return (
    <div style={{ height: '100%', position: 'relative' }}>
      <div ref={mountRef} style={{ width: '100%', height: '100%' }} />
      
      {isLoading && (
        <div style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          color: 'white',
          zIndex: 1000
        }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在加载华发一期3D场景...</div>
        </div>
      )}

      {/* 设备信息弹窗 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <DatabaseOutlined />
            <span>设备详细信息</span>
          </div>
        }
        open={deviceModalVisible}
        onCancel={() => {
          setDeviceModalVisible(false);
          setSelectedDevice(null);
        }}
        footer={null}
        width={800}
      >
        {selectedDevice && (
          <Descriptions
            title={selectedDevice.name}
            bordered
            column={2}
            size="small"
          >
            <Descriptions.Item label="设备ID">{selectedDevice.id}</Descriptions.Item>
            <Descriptions.Item label="设备类型">
              <Tag color="blue">电梯</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="所属建筑">{selectedDevice.buildingName}</Descriptions.Item>
            <Descriptions.Item label="设备状态">
              <Tag color={selectedDevice.status === 'online' ? 'green' : 'red'}>
                {selectedDevice.status === 'online' ? '在线' : '离线'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="位置">{selectedDevice.location}</Descriptions.Item>
            <Descriptions.Item label="制造商">{selectedDevice.manufacturer}</Descriptions.Item>
            <Descriptions.Item label="型号">{selectedDevice.model}</Descriptions.Item>
            <Descriptions.Item label="安装日期">{selectedDevice.installDate}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 楼宇信息弹窗 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <HomeOutlined />
            <span>楼宇详细信息</span>
          </div>
        }
        open={buildingModalVisible}
        onCancel={() => {
          setBuildingModalVisible(false);
          setSelectedBuilding(null);
        }}
        footer={null}
        width={800}
      >
        {selectedBuilding && (
          <Descriptions
            title={selectedBuilding.name}
            bordered
            column={2}
            size="small"
          >
            <Descriptions.Item label="楼宇ID">{selectedBuilding.id}</Descriptions.Item>
            <Descriptions.Item label="楼宇类型">
              <Tag color={
                selectedBuilding.type === 'residential' ? 'blue' :
                selectedBuilding.type === 'commercial' ? 'purple' : 'cyan'
              }>
                {selectedBuilding.type === 'residential' ? '住宅楼' :
                 selectedBuilding.type === 'commercial' ? '商业楼' : '办公楼'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="楼层数">{selectedBuilding.floors} 层</Descriptions.Item>
            <Descriptions.Item label="楼宇状态">
              <Tag color={
                selectedBuilding.status === 'normal' ? 'green' :
                selectedBuilding.status === 'medium' ? 'orange' : 'red'
              }>
                {selectedBuilding.status === 'normal' ? '正常' :
                 selectedBuilding.status === 'medium' ? '中等状态' : '较少状态'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="入住率">
              <Progress percent={selectedBuilding.occupancy} size="small" />
            </Descriptions.Item>
            <Descriptions.Item label="电梯数量">{selectedBuilding.elevators.length} 部</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default Phase1View;